#!/usr/bin/python
# -*- coding: utf-8 -*-

'''
参考: http://pypi.python.org/pypi/multiprocessing/#downloads
'''

__author__ = 'lyj'

import MySQLdb
import multiprocessing

def main():
    tablename = 'address_demographics'
    inserts = []
    id = 0
    max_id = 1000000
    while id < max_id:
        sql = """
        INSERT IGNORE INTO `%s` (person_id)
        SELECT person_id
          FROM `people`
         WHERE id BETWEEN %d AND %d
        """ % (tablename,id,(id + 100000))
        inserts.append(sql)
        id += 100001
    pool = multiprocessing.Pool(multiprocessing.cpu_count())
    pool.map(sqlWorkerInsert, inserts, 1)
    pool.close()
    pool.join()

def sqlWorkerInsert(sql):
    print '* sqlWorkerInsert'
    print sql
    conn = MySQLdb.connect(host = "127.0.0.1",
                           user = "root",
                           passwd = "",
                           db = "test")
    cursor = conn.cursor()
    # Need to do this since AUTOCOMMIT = 0 by default (wtf?)
    cursor.execute("SET AUTOCOMMIT=1")
    cursor.execute(sql)
    cursor.close()
    conn.close()

if __name__ == '__main__':
    main()